package com.finapps.stopspend.dao;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import org.apache.commons.io.FileUtils;

import android.content.Context;
import android.database.CursorJoiner.Result;
import android.database.sqlite.SQLiteDatabase;


public class Database {
	private static Database INSTANCE=new Database();
	
	private static final String DATABASE_NAME= "stopSpend.db";
	private static final int DATABASE_VERSION=1;
	private StopSpendSqlLiteHelper dbStopSpend;
	private Context context;
	private Lock lock=new ReentrantLock(true);
	private SQLiteDatabase opened;
	
	public static void init(Context context) {
		INSTANCE.context=context;
	}
	
	public static Database get() {
		return INSTANCE;
	}
	
	public SQLiteDatabase open() {
		lock.lock();
		if(opened==null) { //Ens guardem instancia oberta per si dintre mateix fil s'intenta fer dos cops open
			dbStopSpend=new StopSpendSqlLiteHelper(context,DATABASE_NAME,null,DATABASE_VERSION);
			opened=dbStopSpend.getWritableDatabase();
		}
		return opened;
	}

	public void close() {
		try {
			dbStopSpend.close();
		} finally {
			dbStopSpend=null;
			opened=null;
			lock.unlock();
		}
	}


}
